package org.jpush.utils;

public class DataBuffer
{
    protected byte pBuffer[];
    protected int uSize;
    protected int uMaxSize;

	public DataBuffer(int uMaxSize)
	{
	    uSize = 0;
	    allocate(uMaxSize);
	}

	public DataBuffer()
	{
	    uSize = 0;
	    pBuffer = null;
	}

	void allocate( int uMaxSize )
	{
	    this.uMaxSize = uMaxSize;
	    pBuffer = new byte[uMaxSize];
	}

	public boolean append( byte[] _pBuffer )
	{
	    return append(_pBuffer, _pBuffer.length);
	}

	public boolean append( byte[] _pBuffer, int _uSize )
	{
	    if(getRemainingSize() < _uSize)
	        return false;

	    //Copy the data
	    System.arraycopy(_pBuffer, 0, pBuffer, uSize, _uSize);

	    //Update the size of the buffer.
	    uSize += _uSize;

	    return true;
	}

	public void pop( int _uSize )
	{
		// Copy to temp array first
		int newSize = uSize-_uSize;
		byte []temp = new byte[newSize];
	    System.arraycopy(pBuffer, _uSize, temp, 0, newSize);
	    
	    // Copy back
	    System.arraycopy(temp, 0, pBuffer, 0, newSize);
	    uSize-=_uSize;
	}

	public int getDataSize()
	{
	    return uSize;
	}

	public int getMaxDataSize()
	{
	    return uMaxSize;
	}

	public byte[] getBuffer()
	{
	    return pBuffer;
	}

	public int getRemainingSize()
	{
	    return uMaxSize - uSize;
	}

	public void growSize( int growBy )
	{
	    uSize += growBy;
	}

	public byte getAt( int offset )
	{
	    return pBuffer[offset];
	}
	
	public String getAsString()
	{
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < uSize; i ++)
		{
			sb.append((char)pBuffer[i]);
		}
		
		return sb.toString();
	}

}
